import { RSA } from './rsa'
import MD5 from 'md5'
import crypto from 'crypto'

var STATIC_KEY = '-----BEGIN PUBLIC KEY-----MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC6Mz8bkEaB9AED/afvk0g/dcdKZrTAcSoxICGjX6gntY6dO4IsBOFCLvhF1FiK5BUs/dni83t55kZLgjCf+sBbCoqO5Kfk/7hINJv8yTjJ+wEXLKXjL4uBZBAdYeEjnLoZtahCls5wPFdrYcflxuHyj6N2wLRgH5F9VnrS3WZYzQIDAQAB-----END PUBLIC KEY-----'
var keyCode = MD5(String(new Date().getTime()))
// 数据aes加密
export function AES (data, iv = '') {
  data = JSON.stringify(data)
  iv = iv || ''
  var clearEncoding = 'utf8'
  var cipherEncoding = 'base64'
  var cipherChunks = []
  var cipher = crypto.createCipheriv('aes-256-ecb', keyCode, iv)
  cipher.setAutoPadding(true)
  cipherChunks.push(cipher.update(data, clearEncoding, cipherEncoding))
  cipherChunks.push(cipher.final(cipherEncoding))
  const body = cipherChunks.join('')
  const key = RASCode()
  return { body, key }
}
// key非对称加密
export function RASCode () {
  var encryptRsa = new RSA.RSAKey()
  encryptRsa = RSA.KEYUTIL.getKey(STATIC_KEY)
  var encStr = encryptRsa.encrypt(keyCode)
  encStr = RSA.hex2b64(encStr)
  return encStr
}
